package com.fang.transfer.file.client.listener;

import com.fang.transfer.file.client.AppContext;
import com.fang.transfer.file.client.thread.UDPHoleService;
import com.fang.transfer.file.common.RequestListener;
import com.fang.transfer.file.common.code.ServiceSendCode;
import com.fang.transfer.file.common.model.TransferFileRequest;
import com.fang.transfer.file.common.model.User;

/**
 * 修改发送方接收方 udp地址,并开始打洞
 */
public class UDPAddrUpdateListener extends RequestListener<TransferFileRequest> {

    @Override
    public void handle(TransferFileRequest param) {
        TransferFileRequest request = AppContext.transferFileRequestMap.get(param.getId());
        String role = request.getRole();

        if ("1".equals(role)) {
            updateAddrInfo(param.getReceiveUser(), request.getReceiveUser());
        } else {
            updateAddrInfo(param.getSendUser(), request.getSendUser());
        }
        AppContext.poolExecutor.execute(new UDPHoleService(request));
    }

    private void updateAddrInfo(User source, User target) {
        target.setHost(source.getHost());
        target.setPort(source.getPort());
    }

    @Override
    public String getCode() {
        return ServiceSendCode.UDP_ADDR_TO_CLIENT;
    }
}
